
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Stub {

	protected String serverAddress;
	protected int portNumber = 40308; 
    static final boolean debug = false;
    
    /**
     * @param message Message is for example /BANK/id/ACCOUNT/id/WITHDRAW/amount
     * @param response true if a response is expected from the server
     * @return the response from the server or null
     */
	protected String sendAndGetResponseMessage(String message, boolean response) {
		Socket socket = connectToServer(serverAddress);
		String res = null;

		if (socket != null) {
			debugMsg("Connected to " + socket);
			try {
				PrintWriter toServer = new PrintWriter(socket.getOutputStream(),true);

				debugMsg("STUB: Sending to server: " + message);
				toServer.println("GET " + message + " HTTP/1.0\n\n");

				if(response){
					BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					String responseHeader = fromServer.readLine();
	                if(responseHeader != null){
	                	String responseField;
	                	while ( (responseField = fromServer.readLine()) != null) {
	                        if( responseField.equals("") ) break; //end of request
	                        //Ignores any fields
	                    }
	                	res = fromServer.readLine();
	                	debugMsg("STUB: Response from server is: " + res);
	                }
				}

				socket.close();
			} catch (IOException e) {
				// We ignore IOExceptions
				System.out.println(e);
			}
		}
		return res;
	}

	private Socket connectToServer(String serverName) {
		Socket res = null;
		try {
			res = new Socket(serverName,portNumber);
		} catch (IOException e) {
			// We return null on IOExceptions
		}
		return res;
	}

    private void debugMsg(String msg){
        if(debug){
            System.out.println(msg);
        }
    }
}
